package com.pine.service.pineframework.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysRoleQueryRequest;
import com.pine.common.beans.pineframework.response.SysRoleQueryResponse;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.PageResponse;
import com.pine.dao.pineframework.entity.SysRole;
import com.pine.manager.pineframework.SysRoleManager;
import com.pine.manager.pineframework.bo.SysRoleBo;
import com.pine.manager.pineframework.convertors.SysRoleConvertor;
import com.pine.manager.pineframework.query.SysRoleQuery;
import com.pine.service.pineframework.SysRoleService;
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Slf4j
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleManager sysRoleManager;

    @Resource
    private SysRoleConvertor sysRoleConvertor;

    private static final Map<String, SFunction<SysRole, ?>> COLUMNS_FUNCTION_MAP;

    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", SysRole::getId
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public SysRoleQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        SysRoleBo sysRoleBo = sysRoleManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, SysRole::getId));
        return sysRoleConvertor.entityBoToQueryResponse(sysRoleBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<SysRoleQueryResponse> list(SysRoleQueryRequest request) {
        SysRoleQuery sysRoleQuery = sysRoleConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(sysRoleQuery)) {
            List<SysRoleBo> sysRoleList = sysRoleManager.list(sysRoleQuery);
            if (ObjectUtils.isNotEmpty(sysRoleList)) {
                return sysRoleList.stream()
                        .map(sysRoleConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<SysRoleQueryResponse> listPages(PageRequest<SysRoleQueryRequest> request) {
        try {
            // 分页查询
            IPage<SysRoleBo> sysRolePage = sysRoleManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(sysRolePage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param sysRolePage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<SysRoleQueryResponse> safelyConvertPage(IPage<SysRoleBo> sysRolePage) {
        if (sysRolePage == null || sysRolePage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<SysRoleQueryResponse> responses = sysRolePage.getRecords().parallelStream()
                .map(sysRoleBo -> sysRoleConvertor.entityBoToQueryResponse(sysRoleBo))
                .collect(Collectors.toList());

        return PageUtil.convertPage(sysRolePage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<SysRoleQuery> transformToQuery(PageRequest<SysRoleQueryRequest> request) {
        SysRoleQuery sysRoleQuery = sysRoleConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), sysRoleQuery);
    }
}
